﻿using DotNetty.Transport.Channels;

namespace Athena.Transport.DotNetty.ChannelHandlerAdapers
{
    using Message;
    public class DefaultChannelHandlerAdaper : ChannelHandlerAdapter
    {
        private readonly DotNettyTransportClientFactory _dotNettyTransportClientFactory;

        public DefaultChannelHandlerAdaper(DotNettyTransportClientFactory dotNettyTransportClientFactory)
        {
            _dotNettyTransportClientFactory = dotNettyTransportClientFactory;
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            _dotNettyTransportClientFactory.DestoryClient(context.Channel.GetAttribute(DotNettyTransportClientFactory.ClientEndPointKey).Get());
        }

        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var rpcTransportMessage = message as RpcTransportMessage;
            var messageListener = context.Channel.GetAttribute(DotNettyTransportClientFactory.MessageListenerKey).Get();
            var messageSender = context.Channel.GetAttribute(DotNettyTransportClientFactory.MessageSenderKey).Get();
            messageListener.OnReceived(messageSender, rpcTransportMessage);
        }
    }
}
